// Copyright (C) 2010 nodchip.

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2.0.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License 2.0 for more details.

// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/

// This file must be compiled under Windows only.

#ifdef _MSC_VER

#include "FiberCoroutine.h"

namespace LLVMJit
{

FiberCoroutine::FiberCoroutine(FiberCoroutine* that)
{
	stackSize = 0;
	theOther = that;
}

FiberCoroutine::FiberCoroutine(size_t stackSize)
{
	fiber = NULL;
	this->stackSize = stackSize;
	theOther = new FiberCoroutine(this);
}

void FiberCoroutine::SetEntryPoint(Coroutine::EntryPoint entryPoint, void* argument)
{
	LPFIBER_START_ROUTINE start = (LPFIBER_START_ROUTINE)entryPoint;
	theOther->fiber = ::CreateFiber(stackSize, start, argument);
}

void FiberCoroutine::Yield()
{
	if (fiber)
	{
		::SwitchToFiber(theOther->fiber);
	}
	else
	{
		fiber = ::ConvertThreadToFiber(0);
		::SwitchToFiber(theOther->fiber);
		::ConvertFiberToThread();
		fiber = NULL;
	}
}

FiberCoroutine::~FiberCoroutine()
{
	if (fiber != NULL)
	{
		::DeleteFiber(fiber);
		fiber = NULL;
	}
	if (theOther != NULL)
	{
		// to prevent deleting twice
		if (theOther->theOther != NULL)
		{
			theOther->theOther = NULL;
		}
		delete theOther;
		theOther = NULL;
	}
}

}

#endif // MSC_VER